<template>
  <page-view class="login">
    <page-header title="登录" :show-back="true" />
    <div class="content-box">
      <Form @submit="onSubmit">
        <cell-group inset>
          <!-- 通过 pattern 进行正则校验 -->
          <field
            v-model="zh"
            name="用户名"
            label="用户名"
            placeholder="请输入用户名"
            :rules="[{ required: true, message: '请输入用户名' }]"
          />
          <!-- 通过 validator 进行函数校验 -->
          <field
            type="password"
            v-model="password"
            name="密码"
            label="密码"
            placeholder="请输入密码"
            :rules="[{ validator: validatorPassword }]"
          />
          <!-- 通过 validator 返回错误提示 -->
        </cell-group>
        <Drag @unlock="unlock" />
        <div style="margin: 16px">
          <Button
            round
            block
            type="primary"
            native-type="submit"
            :loading="loading"
            loading-text="正在登陆"
            :disabled="loading"
            >提交</Button
          >
        </div>
      </Form>
      <div class="tips">
        还没有账号？去<router-link :to="{ name: 'Register' }">注册</router-link>
      </div>
    </div>
  </page-view>
</template>

<script>
import PageHeader from "@/components/PageHeader.vue";
import { Form, Field, CellGroup, Button, Toast } from "vant";
import { ref, reactive, toRefs } from "vue";
import { useRouter, useRoute } from "vue-router";
import { useStore } from "vuex";
import api from "@/utils/api";
import Drag from "@/components/Drag.vue";
export default {
  name: "Login",
  components: {
    Toast,
    Form,
    Field,
    CellGroup,
    Button,
    Drag,
  },

  setup() {
    //创建仓库的实例化对象
    const store = useStore();
    //创建路由的实例化对象
    const router = useRouter();
    const route = useRoute();
    const loading = ref(false);
    //创建一个数据对象存储数据
    let userInfo = reactive({
      zh: "",
      password: "",
    });
    //校验密码 validatorPassword
    const validatorPassword = (val) => {
      if (val.trim().length < 6 || val.trim().length > 16) {
        return "密码长度不对";
      }
    };

    //用于滑块解锁
    let clock = false;
    function unlock() {
      clock = true;
    }

    const onSubmit = (value) => {
      if (clock == false) {
        Toast.clear(true);
        Toast.fail("请滑动滑块解锁");
        return;
      }
      checkLogin();
    };
    const checkLogin = async () => {
      //表单提交之前先解锁否则直接返回
      Toast.loading({
        message: "登陆中...",
        forbidClick: true,
        duration: 0,
      });

      //控制禁用（提交）按钮
      loading.value = true;
      //   模拟人多的时候
      setTimeout(async () => {
        try {
          //   发送请求
          let res = await api.userInfo.checkLogin(userInfo);
          //清除提示
          console.log(res);
          Toast.clear(true);
          Toast.success("登陆成功");
          //   仓库存储用户信息
          console.log(store.state.token);
          store.commit("setUserInfo", res.loginUserInfo);
          store.commit("setToken", res.token);

          //   跳转页面

          if (route.query.redirect) {
            router.push(route.query.redirect);
          } else {
            router.back();
          }
        } catch (error) {
          //   失败提示
          Toast.fail("登陆失败");
        } finally {
          loading.value = false; //不管请求成功与否都终止掉加载圈圈
        }
      }, 1000);
    };

    return {
      ...toRefs(userInfo),
      checkLogin,
      loading,
      unlock,
      onSubmit,
      validatorPassword,
    };
  },
};
</script>

<style lang="scss" scoped>
.login {
  overflow: auto;
  .content-box {
    flex: 1;
    .tips {
      display: flex;
      justify-content: center;
      align-items: center;
      text-align: center;
      margin-top: 16px;
      color: #999;
      a {
        color: $primaryColor;
      }
    }
  }
}
</style>
